/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imenu.websocket;

// Please note that Web sockets are not enabled by default in Glassfish. 

import com.sun.grizzly.websockets.DataFrame;
import com.sun.grizzly.websockets.NetworkHandler;
import com.sun.grizzly.websockets.WebSocket;
import com.sun.grizzly.websockets.WebSocketApplication;
import com.sun.grizzly.websockets.WebSocketListener;
import java.io.IOException;

// To enable them you must execute the following single-line command on your domain:
// asadmin set configs.config.server-config.network-config.protocols.protocol.http-listener-1.http.websockets-support-enabled=true
/**
 *
 * @author yunzi
 */
public class YuncaiApplication extends WebSocketApplication {

    public WebSocket createSocket(NetworkHandler handler,
            WebSocketListener... listeners) throws IOException {
        return new OrderWebSocket(listeners);
    }

    @Override
    public void onMessage(WebSocket socket, String text) {
        System.out.println("YuncaiApplication.isApplicationRequest() WebSocket socket = " + socket +" text = "+text);
        super.onMessage(socket, text);
    }

    @Override
    public void onMessage(WebSocket socket, byte[] bytes) {
        System.out.println("YuncaiApplication.isApplicationRequest() WebSocket socket = " + socket +" bytes = "+bytes);
        super.onMessage(socket, bytes);
    }

    
    public void onMessage(WebSocket socket, DataFrame frame) throws IOException {
        System.out.println("YuncaiApplication.onMessage() WebSocket socket = " + socket +" frame = "+frame);
        final String data = frame.getTextPayload();
        for (WebSocket webSocket : getWebSockets()) {
            if (socket != webSocket) {
                webSocket.send(data);
            }
        }
    }

    
    @Override
    public boolean isApplicationRequest(com.sun.grizzly.tcp.Request request) {
        System.out.println("YuncaiApplication.isApplicationRequest() request=" + request);
        //throw new UnsupportedOperationException("Not supported yet.");
        return true;
    }
     
    
    @Override
    public boolean add(WebSocket socket) {
        System.out.println("YuncaiApplication.add(WebSocket socket)");
        return super.add(socket);
    }

    @Override
    public void onConnect(WebSocket socket) {
        System.out.println("YuncaiApplication.onConnect(WebSocket socket)");
        super.onConnect(socket);
    }

    @Override
    public void onClose(WebSocket socket) {
        System.out.println("YuncaiApplication.onClose(WebSocket socket)");
        super.onClose(socket);
    }

    @Override
    public boolean remove(WebSocket socket) {
        System.out.println("YuncaiApplication.remove(WebSocket socket)");
        return super.remove(socket);
    }

}